		var appWidth = 0, appHeight = 0;
        var imgWidth = 0, imgHeight = 0;
        var scaleX = 1, scaleY = 1;
        var mapNodeValueCount = {};
        // $("#screenshot").attr("width",$("#screenshot").parent().css("width"));
        var WebSocketIP = "192.168.164.129";// getParameterByName("WebSocketIP");
        var webSocketPort = "9765";// getParameterByName("webSocketPort");
        var sourcePort = "9766";// getParameterByName("sourcePort");
        var screenWidth = 720;// getParameterByName("screenWidth");
        var screenHeight = 1280;// getParameterByName("screenHeight");
        var recordFlag=false;
        var canBeUsed=false;
        var chooseDeviceId;
        var serverURL="";
        var arrKeyAttrs = ['resource-id', 'name', 'text'];
        var pictureBase64Data;
        var paltform = '';
        var tapX=0;
        var tapY=0;

        // var editor ;
        var appTree;

        function showCoords(c) {
            // alert(c);
            $('#x1').val(c.x);
            $('#y1').val(c.y);
            $('#x2').val(c.x2);
            $('#y2').val(c.y2);
            $('#w').val(c.w);
            $('#h').val(c.h);
        };

        function clearCoords()
        {
            $('#coords input').val('');
        }
        var jcroppictrueFlag=true;
        function jcroppictrue(){
        	if(jcroppictrueFlag==true){
        		jcroppictrueFlag=false;
        		$("#jcroppictrueId").html("停止截图");
        		$("#screenshot").parent().css("display","none");
        		pictureBase64Data = screenshot_picture();
        		// $("#screenshot2").attr('src',pictureBase64Data);
        		$("#jcroppictrueDiv").css("display","");
        		var jcroppictrueHtml='<div class="row">';
        		
        		jcroppictrueHtml+='<div class="span12">';
        		jcroppictrueHtml+='<div class="jc-demo-box">';
        		jcroppictrueHtml+='<p style="margin: 0;">';
        		jcroppictrueHtml+='<img id="screenshot2" style="height: 500px;"src="data:image/png;base64,'+pictureBase64Data+'" data-holder-rendered="true">';
        		jcroppictrueHtml+='</p></div></div></div>';
        		
        		$("#jcroppictrueDiv").html(jcroppictrueHtml);
        		var jcrop_api;

                $('#screenshot2').Jcrop({
                    onChange:   showCoords,
                    onSelect:   showCoords,
                    onRelease:  clearCoords
                },function(){
                    jcrop_api = this;
                });
        	}else{
        		$("#jcroppictrueId").html("开始截图");
        		$("#jcroppictrueDiv").css("display","none");
        		$("#screenshot").parent().css("display","");
        		jcroppictrueForAjax();
        		jcroppictrueFlag=true;
        	}
        }
        var chooseRegionFlag=true;
        function chooseRegion(){
        	if(chooseRegionFlag==true){
        		chooseRegionFlag=false;
        		$("#chooseRegionId").html("确认区域");
        		$("#screenshot").parent().css("display","none");
        		pictureBase64Data = screenshot_picture();
        		$("#jcroppictrueDiv").css("display","");
        		var jcroppictrueHtml='<div class="row">';
        		
        		jcroppictrueHtml+='<div class="span12">';
        		jcroppictrueHtml+='<div class="jc-demo-box">';
        		jcroppictrueHtml+='<p style="margin: 0;">';
        		jcroppictrueHtml+='<img id="screenshot2" style="height: 500px;"src="data:image/png;base64,'+pictureBase64Data+'" data-holder-rendered="true">';
        		jcroppictrueHtml+='</p></div></div></div>';
        		
        		$("#jcroppictrueDiv").html(jcroppictrueHtml);
        		var jcrop_api;

                $('#screenshot2').Jcrop({
                    onChange:   showCoords,
                    onSelect:   showCoords,
                    onRelease:  clearCoords
                },function(){
                    jcrop_api = this;
                });
        	}else{
        		$("#chooseRegionId").html("选择区域");
        		$("#jcroppictrueDiv").css("display","none");
        		$("#screenshot").parent().css("display","");
        		var bili = screenHeight/500;
        		$("#start-X").val($('#x1').val());
        		$("#start-Y").val($('#y1').val());
        		$("#width").val($('#w').val());
        		$("#height").val($('#h').val());
        		chooseRegionFlag=true;
        	}
        }
        function jcroppictrueForAjax(){
        	
        	var data = {"startX":$('#x1').val(),
        			"startY":$('#y1').val(),
        			"width":$('#w').val(),
        			"height":$('#h').val(),
        			"pictureBase64Data":pictureBase64Data};
        	$.ajax({
        		url :'../obj/jcroppictrueForAjax',
        		data:data,
        		async : false,
        		type : "POST",
        		success :function(data){
	        		 if(data.status==1){
	        			 $("#controlImg").attr("src","data:image/png;base64,"+data.data);
	        		 }else{
	        			 layer.alert(data.errorMsg, {
	        	        	icon: 5,
	        	        	title: "错误"
	        	        });
	        		 }
	        		
	        	},
	        	error:function(data){
	        		layer.alert(data.errorMsg, {
	        		icon: 5,
	        		title: "错误"
	        		});
	        	}
        	});
        }
        
        function screenshot_picture() {
            var blob = $("#screenshot").attr("src");
            var img = document.createElement("img");
            img.src = blob;
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img,0,0,img.width,img.height);
            var base64 = canvas.toDataURL("image/png");
            var base64PictureCode = base64.replace("data:image/png;base64,","");
            return base64PictureCode;
        }
        function scanAllNode(){
           mapNodeValueCount = {};
           if("ios"==paltform){
        	   		scanNode(appTree);
           }else{
	        	   if(appTree instanceof Array){
	           	    var list = appTree.filter(i => i !== null && typeof i === 'object' && i.package !== 'com.android.systemui');
	                appTree = list[0];
	           }
	           scanNode(appTree);
           }
            
        }

        // 从左边读取限制长度的字符串
        function leftstr(text, limit) {
            var substr = '';
            var count = 0;
            var char;
            for (var i = 0, len = text.length; i < len; i++) {
                char = text.charCodeAt(i);
                substr += text.charAt(i);
                count += char > 255 ? 2 : 1;
                if (count >= limit) {
                    return substr;
                }
            }
            return substr;
        }


        function scanNode(node){
         	
            arrKeyAttrs.forEach(function(name){
                var value = node[name];
                if(value){
                    var mapCount = mapNodeValueCount[name] || {};
                    mapCount[value] = mapCount[value] && mapCount[value] + 1 || 1;
                    mapNodeValueCount[name] = mapCount;
                }
            })
            node.class = node.class || ('XCUIElementType' + node.type);
            var bounds = node.bounds || '';
            if(bounds==''&& "ios"==paltform){
	            	var rect = node.rect;
	            	  node.bounds = [
	            	    rect.x,
	            	    rect.y,
	            	    rect.width,
	            	    rect.height,
	            	  ];
            };
            bounds = node.bounds || '';
            var match;
            if("ios"==paltform){
            		node.startX = parseInt(bounds[0], 10);
                node.startY = parseInt(bounds[1], 10);
                node.endX = parseInt(bounds[2], 10);
                node.endY = parseInt(bounds[3], 10);
                node.boundSize = (node.endX - node.startX) * (node.endY - node.startY);
            }else{
            		match = bounds.match(/^\[([\d\.]+),([\d\.]+)\]\[([\d\.]+),([\d\.]+)\]$/);
            		if(match){
                        node.startX = parseInt(match[1], 10);
                        node.startY = parseInt(match[2], 10);
                        node.endX = parseInt(match[3], 10);
                        node.endY = parseInt(match[4], 10);
                        node.boundSize = (node.endX - node.startX) * (node.endY - node.startY);
                    }
                 match = bounds.match(/\{([\d\.]+),\s*([\d\.]+)\},\s*\{([\d\.]+),\s*([\d\.]+)\}/);
                 if(match){
                        node.startX = parseInt(match[1], 10);
                        node.startY = parseInt(match[2], 10);
                        node.endX =  node.startX + parseInt(match[3], 10);
                        node.endY = node.startY + parseInt(match[4], 10);
                        node.boundSize = (node.endX - node.startX) * (node.endY - node.startY);
                  }
            }
            
            var childNodes = node.children || node.node;
            if(childNodes){
                node.children = childNodes;
                if(!Array.isArray(childNodes)){
                    childNodes = [childNodes];
                }
                var childNode;
                for(var i=0;i<childNodes.length;i++){
                    childNode = childNodes[i];
                    childNode.parentNode = node;
                    scanNode(childNode);
                }
            }
        }

        // get node info by x,y
        function getNodeInfo(x, y){
            var nodeInfo = {};
            var bestNodeInfo = {
                node: null,
                boundSize: 0
            };
            getBestNode(appTree, x, y, bestNodeInfo);
            var bestNode = bestNodeInfo.node;
            if(bestNode){
                var text = bestNode.text || bestNode.label;
                if(text){
                    text = text.replace(/\s*\r?\n\s*/g,' ');
                    text = text.replace(/^\s+|\s+$/g, '');
                    var textLen = byteLen(text);
                    text = textLen > 20 ? leftstr(text, 20) + '...' : text;
                    nodeInfo.text = text;
                }
                nodeInfo.path = getNodeXPath(bestNode);
            }
            else{
                nodeInfo.x = x;
                nodeInfo.y = y;
            }
            return nodeInfo;
        }
        function getBestNode(node, x, y, bestNodeInfo){
            if(node.boundSize && x >= node.startX && x <= node.endX && y >= node.startY && y <= node.endY){
                var childNodes = node.children;
                if(childNodes){
                    if(!Array.isArray(childNodes)){
                        childNodes = [childNodes];
                    }
                    for(var i=0;i<childNodes.length;i++){
	                    	getBestNode(childNodes[i], x, y, bestNodeInfo);
                    }
                }
                else{
                    if(bestNodeInfo.node === null || node.boundSize <= bestNodeInfo.boundSize){
                        bestNodeInfo.node = node;
                        bestNodeInfo.boundSize = node.boundSize;
                    }
                }
            }
        }
        function getNodeXPath(node){
            var XPath = '', index;
            while(node){
                var attrName, attrValue;
                for(var i=0;i<arrKeyAttrs.length;i++){
                    attrName = arrKeyAttrs[i];
                    attrValue = node[attrName];
                    if(attrValue && mapNodeValueCount[attrName][attrValue] === 1){
                        XPath = '/*[@'+attrName+'="'+attrValue+'"]' + XPath;
                        return '/'+XPath;
                    }
                }
                index = getNodeClassIndex(node)
                XPath = '/' + node['class'] + (index > 1 ? '['+index+']' : '') + XPath;
                node = node.parentNode;
            }
            return '/'+XPath;
        }
        function getNodeClassIndex(node){
            var index = 0;
            var className = node.class;
            var parentNode = node.parentNode;
            if(className && parentNode && Array.isArray(parentNode.node) && parentNode.node.length > 1){
                var childNodes = parentNode.node, childNode;
                index = -1;
                for(var i=0;i<childNodes.length;i++){
                    childNode = childNodes[i];
                    if(childNode.class === className){
                        index ++;
                        if(childNode === node){
                            break;
                        }
                    }
                }
            }
            return index + 1;
        }

        // 计算字节长度,中文两个字节
        function byteLen(text) {
            var count = 0;
            for (var i = 0, len = text.length; i < len; i++) {
                char = text.charCodeAt(i);
                count += char > 255 ? 2 : 1;
            }
            return count;
        }


        function saveCommand(cmd, data) {
            var cmdData = {
                cmd: cmd,
                data: data
            };

            var data = {
                type: 'command',
                data: cmdData
            };
            socket.send(JSON.stringify(data));

        }

        function request_get() {
            sourceSaveCommand('getSource');
        }

        function sourceSaveCommand(cmd, data) {
            var cmdData = {
                cmd: cmd,
                data: data
            };

            var data = {
                type: 'command',
                data: cmdData
            };
            sourceSocket.send(JSON.stringify(data));

        }

// alert(sourcePort +"-----"+webSocketPort+"-----"+WebSocketIP);
        var socket;

        var sourceSocket;
        
        var ws;

        var downTime = 0;
        function recorddevice(deviceId,platform) {
        		if('ios'==platform){
        			chooseDeviceId = deviceId;
        		 	var data = {"deviceId":deviceId};
                	$.ajax({
                		url :'../obj/recorddevice',
                		data:data,
                		async : false,
                		type : "POST",
                		success :function(data){
        	        		
        	        	},
        	        	error:function(data){
        	        		layer.alert(data.errorMsg, {
        	        		icon: 5,
        	        		title: "错误"
        	        		});
        	        	}
                	});
        			
        			
		        		paltform = 'ios';
		        		var screenshot = document.getElementById('screenshot');
		        		var WSURL = "ws://localhost:8080/websocket";
        		
				    function BackFrame() {
				        this.blob = null
				    }
				    BackFrame.prototype.swap = function (blob) {
				        this.blob = blob
				    }
				    BackFrame.prototype.consume = function () {
				        var blob = this.blob
				        this.blob = null
				        return blob
				    }
				    BackFrame.prototype.destroy = function () {
				        this.consume()
				    }
				    // FrontFrame takes a blob from the BackFrame and
					// loads it into an image.
				    // There are two FrontFrames. One is always loading
					// the next image and one
				    // is always being used to render the latest fully
					// loaded image. They're
				    // swapped once loading completes and the process
					// repeats.
				    function FrontFrame(name) {
				        this.name = name
				        this.blob = null
				        this.image = new Image()
				        this.url = null
				        this.loading = false
				        this.loaded = false
				        this.fresh = false
				        this.onLoad = function () {
				            this.loading = false
				            this.loaded = true
				            this.fresh = true
				        }.bind(this)
				        this.onError = function () {
				            this.loading = false
				            this.loaded = false
				        }.bind(this)
				    }
				    FrontFrame.prototype.load = function (blob) {
				        // If someone's calling load() they're already
						// sure that they don't need
				        // the the current frame anymore.
				        this.reset()
				        // Convenience check that must come after the
						// reset.
				        if (!blob) {
				            return
				        }
				        this.blob = blob
				        this.url = URL.createObjectURL(this.blob)
				        this.loading = true
				        this.loaded = false
				        this.fresh = false
				        this.image.onload = this.onLoad
				        this.image.onerror = this.onError
				        this.image.src = this.url
				    }
				    FrontFrame.prototype.reset = function () {
				        this.loading = false
				        this.loaded = false
				        if (this.blob) {
				            this.blob = null
				            URL.revokeObjectURL(this.url)
				            this.url = null
				        }
				    }
				    FrontFrame.prototype.consume = function () {
				        if (!this.fresh) {
				            return null
				        }
				        this.fresh = false
				        return this
				    }
				    FrontFrame.prototype.destroy = function () {
				        this.reset()
				        this.image = null
				    }
				    function Pipeline() {
				        this.back = new BackFrame()
				        this.mid = new FrontFrame('mid')
				        this.front = new FrontFrame('front')
				    }
				    Pipeline.prototype.push = function (blob) {
				        this.back.swap(blob)
				        // If the mid frame isn't loading or waiting to
						// be consumed, let's
				        // ask it to load this new frame to speed up
						// things.
				        if (!this.mid.loading && !this.mid.loaded) {
				            this.mid.load(this.back.consume())
				        }
				    }
				    Pipeline.prototype.consume = function () {
				        if (this.mid.loaded) {
				            const mid = this.mid
				            this.mid = this.front
				            this.front = mid
				            this.mid.load(this.back.consume())
				        } else if (!this.mid.loading) {
				            this.mid.load(this.back.consume())
				        }
				        return this.front.consume()
				    }
				    Pipeline.prototype.destroy = function () {
				        this.back.destroy()
				        this.mid.destroy()
				        this.front.destroy()
				    }
				    
				    var pipeline = new Pipeline()
				    var canvas = document.getElementById('screen')
				    ws = new WebSocket(WSURL)
				    ws.binaryType = 'blob'
				    ws.onclose = function () {
				        console.log('onclose', arguments)
				    }
				    ws.onerror = function () {
				        console.log('onerror', arguments)
				    }
				    ws.onmessage = function (message) {
				        // console.log('got jpeg', arguments)
				        var blob = new Blob([message.data], {
				            type: 'image/jpeg'
				        })
				        // pipeline.push(blob)
				        var u = URL.createObjectURL(blob);
                        $('#screenshot').attr('src', u);
                        // 750x1334
                        appWidth = Number(435);// screenshot.naturalWidth;
                        appHeight = Number(670);// screenshot.naturalHeight;
                        imgWidth = screenshot.width;
                        // imgHeight = appHeight/(appWidth/imgWidth);//
						// screenshot.height;
                        imgHeight = screenshot.height;
                        if (imgWidth != 0) {
                            scaleX = appWidth / imgWidth;
                            scaleY = appHeight / imgHeight;
                        }
                        console.log(appWidth+' '+appHeight+' '+imgWidth+' '+imgHeight+' '+scaleX+' '+scaleY);
                        $(".layui-layer-close1").click();
				    }
				    ws.onopen = function () {
				        console.log('onopen', arguments)
				        ws.send('640x360/0')
				    }
        	}else{
        	 	chooseDeviceId = deviceId;
            	$(".layui-layer-close1").click();
            	var data = {"deviceId":deviceId};
            	$.ajax({
            		url :'../obj/recorddevice',
            		data:data,
            		async : false,
            		type : "POST",
            		success :function(data){
    	        		 if(data.status==1){
    	        			 canBeUsed=true;
    	        			 WebSocketIP = data.data.slaveIp;
    	        		     webSocketPort = data.data.webSocketPort;
    	        		     sourcePort = data.data.sourcePort;
    	        		     screenWidth = data.data.screenWidth;
    	        		     screenHeight = data.data.screenHeight;
    	        		     $("#devicesHeights").val(screenHeight);
    	        		     serverURL = data.serverURL;
    	        		 }else{
    	        			 canBeUsed=false;
    	        			 layer.alert(data.errorMsg, {
    	        	        	icon: 5,
    	        	        	title: "错误"
    	        	        });
    	        		 }
    	        		
    	        	},
    	        	error:function(data){
    	        		layer.alert(data.errorMsg, {
    	        		icon: 5,
    	        		title: "错误"
    	        		});
    	        	}
            	});
            	if(!canBeUsed){
            		return;
            	}
        		 socket = new WebSocket('ws://'+WebSocketIP+':'+webSocketPort);
                 sourceSocket = new WebSocket('ws://'+WebSocketIP+':'+sourcePort);
                 var screenshot = document.getElementById('screenshot');

                 var downX = -9999;
                 var downY = -9999;
                 




                 // 打开Socket
                 socket.onopen = function (event) {

                     // 监听消息
                     socket.onmessage = function (event) {
                         // console.log('Client received a message', event);

                         var blob = new Blob([event.data], {type: 'image/jpeg'});
                         var u = URL.createObjectURL(blob);
                         $('#screenshot').attr('src', u);

                         appWidth = Number(screenWidth);// screenshot.naturalWidth;
                         appHeight = Number(screenHeight);// screenshot.naturalHeight;
                         imgWidth = screenshot.width;
                         imgHeight = appHeight/(appWidth/imgWidth);// screenshot.height;
                         if (imgWidth != 0) {
                             scaleX = appWidth / imgWidth;
                             scaleY = appHeight / imgHeight;
                         }
                         console.log(appWidth+' '+appHeight+' '+imgWidth+' '+imgHeight+' '+scaleX+' '+scaleY);

                     };

                     // 监听Socket的关闭
                     socket.onclose = function (event) {
                         console.log('Client notified socket has closed', event);
                     };

                     // 关闭Socket....
                     // socket.close()
                 };

                 sourceSocket.onopen=function (event) {
                     sourceSocket.onmessage = function (event) {
                         // console.log('Client received a message', event);

                         var appInfo = JSON.parse(event.data);
                         var appSource = appInfo.source;

                         appTree = appSource.tree || appSource.hierarchy.node;
                         scanAllNode();
                     };
                 };

                 setInterval("request_get()", 500);// 1000为1秒钟


        	}
        	
           
            $('#screenshot').click(function (event) {
            	
            		if('ios'==paltform){
	            			var _longClickTimeout = 800;
	            			var p = convertPosition(event);
	            			var upX = event.offsetX, upY = event.offsetY;
	            			tapX=p.pageX;
	            	        tapY=p.pageY;    
                        var defer;
                        if (Math.abs(downX - upX) < 20 && Math.abs(downY - upY) < 20) {
	                        defer = tap(Math.floor(p.pageX * scaleX), Math.floor(upY * scaleY))
	                        console.log("Release operation")
                    }
            		 }else{
            			     var upX = event.offsetX, upY = event.offsetY;
                         var clickDuration = new Date().getTime() - downTime;
                         

                         if (Math.abs(downX - upX) < 20 && Math.abs(downY - upY) < 20) {

                             var cmdData = getNodeInfo(Math.floor(upX * scaleX), Math.floor(upY * scaleY));


                             var pressTime = new Date().getTime() - downTime;
                             var duration = (pressTime / 1000).toFixed(2);
                             
                             saveCommand('click', {
                                 touchX: Math.floor(upX * scaleX),
                                 touchY: Math.floor(upY * scaleY)
                             });
                             if(recordFlag){
                             	if(clickDuration>500){
                                     /*
										 * $("#location-X").val(Math.floor(upX *
										 * scaleX));
										 * $("#location-Y").val(Math.floor(upY *
										 * scaleY));
										 */
                                 }else{
                                 	var str;
                                 	if(controlLocationTypeval==1){
                                 		if(cmdData.path){
                                 			str = cmdData.path;
                                 			$("#controlCode").val(str);
                                 		}else{
                                 			$('#controlLocationType').val(2);
                                 			layui.form.render("select");
                                 			$("div[id$='-div']").hide();
                                 			$("#locationType-div").show();
                                 			$("#location-X").val(upX);
                                 			$("#location-Y").val(upY);
                                 		}
                                 	}else{
                                 		/*
										 * $("#location-X").val(Math.floor(upX *
										 * scaleX));
										 * $("#location-Y").val(Math.floor(upY *
										 * scaleY));
										 */
                             			$("#location-X").val(upX);
                             			$("#location-Y").val(upY);
                                 	}
                                 }
                             	recordFlag=false;
                             	$("#recordButtonId").html("开始录制");
                             }
                             downTime = 0;
                         }
                         event.stopPropagation();
                         event.preventDefault();
            		}
            });


            $('#screenshot').on('mousedown', function (event) {
                downX = event.offsetX;
                downY = event.offsetY;
                downTime = new Date().getTime();

                event.stopPropagation();
                event.preventDefault();
            });

            $('#screenshot').on('mouseup', function (event) {
                var upX = event.offsetX, upY = event.offsetY;
                if (Math.abs(downX - upX) >= 20 || Math.abs(downY - upY) >= 20) {
                		if('ios'==paltform){
                			var startX= Math.floor(downX * scaleX);
                			var startY= Math.floor(downY * scaleY);
                			var endX= Math.floor(upX * scaleX);
                			var endY= Math.floor(upY * scaleY);
                			swipe(startX, startY,endX,endY);
                		}else{
                			saveCommand('swipe', {
                                startX: Math.floor(downX * scaleX),
                                startY: Math.floor(downY * scaleY),
                                endX: Math.floor(upX * scaleX),
                                endY: Math.floor(upY * scaleY),
                                duration: 20
                            });
                		}
                    
                }
                event.stopPropagation();
                event.preventDefault();
            });
            
            $('#sendText').on('keypress',function(event){ 
                if(event.keyCode == 13){
                    saveCommand('setText', {
                    	"text": $('#sendText').val()
                    });
                    $('#sendText').val('');
                }  
            });


        }

        function clickFunc(func) {
        		if("ios"==paltform){
        			home();
        		}else{
        			saveCommand(func, '');
        		}
        }
        
        function connectDevice(){
        	recordFlag=true;
        	$("#recordButtonId").html("结束录制");
        }
        function installApp(){
        	var appId = $("#applist").val();
        	saveCommand('install', serverURL+'/wsServices/getappById/'+appId);
        }
       
        function clickFunc(func) {
	    		if("ios"==paltform){
	    			home();
	    		}else{
	    			saveCommand(func, '');
	    		}
        }
        function givebackDevice(){
        	if("ios"==paltform){
        		ws.close();
        	}else{
        		sourceSocket.close();
            	socket.close();
        	}
        	
        	$('#screenshot').attr('src', '');
        	var data = {"deviceId":chooseDeviceId};
        	$.ajax({
        		url :'../device/givebackDevice',
        		data:data,
        		async : false,
        		type : "POST",
        		success :function(data){
	        		 if(data.status==1){
	        		
	        		 }else{
	        			 layer.alert(data.errorMsg, {
	        	        	icon: 5,
	        	        	title: "错误"
	        	        });
	        		 }
	        		
	        	},
	        	error:function(data){
	        		layer.alert(data.errorMsg, {
	        		icon: 5,
	        		title: "错误"
	        		});
	        	}
        	});
        }
        
        function convertPosition(event) {
            var e = event;
            if (e.originalEvent) {
                e = e.originalEvent
            }
            // Ignore mouse right click
            if (e.which === 3) {
                return;
            }
            e.preventDefault()
// calculateBounds()
            var x = e.offsetX - 30
            var y = e.offsetY
            console.log("page x: " + e.offsetX + ", page y: " + e.offsetY)
            var width = $("#screenshot").parent().css("width");
            return {
                e: e,
                x: Math.floor(x / (element.clientWidth - 60) * width),
                y: Math.floor(y / element.clientHeight * 500),
                pageX: x,
                pageY: y,
            }
        }
        
        function tap (x, y) {
        		console.log("x:"+x+",y:"+y);
	        	$.ajax({
	        		// url :'../device/givebackDevice',
	        		url: '../device/tap',
	        		data:{"x":x,"y":y,"recordFlag":recordFlag},
	        		async : false,
	        		type : "POST",
	        		success :function(data){
		        		 if(data=="faild"){
		        			 alert("操作失败");
		        		 }else{
		        			 
		        			 if(recordFlag){
	                         if(controlLocationTypeval==1){
	                        	 	if(data.indexOf('XCUIElementType')==0){
	                        	 		 str = '//'+data;
	                        	 	}else{
	                        	 		 str = '//*[@name="'+data+'"]';
	                        	 	}
	                             if(data==""){
		                            	    $('#controlLocationType').val(2);
	                          			layui.form.render("select");
	                          			$("div[id$='-div']").hide();
	                          			$("#locationType-div").show();
	                          			$("#location-X").val(x);
	                          			$("#location-Y").val(y);
		                           }else{
		                        	   	$("#controlCode").val(str);
		                           }
	                         }else if(controlLocationTypeval==2){
	                            $("#location-X").val(x);
	                            $("#location-Y").val(y);
	                         }
	                      }
	                     recordFlag=false;
	                     $("#recordButtonId").html("开始录制");
	                }
		        	},
		        	error:function(data){
		        		layer.alert(data.errorMsg, {
		        		icon: 5,
		        		title: "错误"
		        		});
		        	}
	        	});
        }
        
        
        function tapHold (x, y,holdTime) {
    		console.log("x:"+x+",y:"+y);
        	$.ajax({
        		// url :'../device/givebackDevice',
        		url: '../device/tapHold',
        		data:{"x":x,"y":y,"holdTime":holdTime},
        		async : false,
        		type : "POST",
        		success :function(data){
	        		 if(data=="success"){
	        		
	        		 }else{
	        			 alert("c操作失败");
	        		 }
	        		
	        	},
	        	error:function(data){
	        		layer.alert(data.errorMsg, {
	        		icon: 5,
	        		title: "错误"
	        		});
	        	}
        	});
    }
         
        
        function swipe (startX, startY,endX,endY) {
    		console.log("x:"+startX+",y:"+startY+"endX:"+endX+",endY:"+endY);
        	$.ajax({
        		// url :'../device/givebackDevice',
        		url: '../device/swipe',
        		data:{"startX":startX,"startY":startY,"endX":endX,"endY":endY},
        		async : false,
        		type : "POST",
        		success :function(data){
	        		 if(data=="success"){
	        		
	        		 }else{
	        			 alert("c操作失败");
	        		 }
	        		
	        	},
	        	error:function(data){
	        		layer.alert(data.errorMsg, {
	        		icon: 5,
	        		title: "错误"
	        		});
	        	}
        	});
    }
        
     function home(){
    		$.ajax({
        		// url :'../device/givebackDevice',
        		url: '../device/home',
        		async : false,
        		type : "POST",
        		success :function(data){
	        		 if(data=="success"){
	        		
	        		 }else{
	        			 alert("c操作失败");
	        		 }
	        		
	        	},
	        	error:function(data){
	        		layer.alert(data.errorMsg, {
	        		icon: 5,
	        		title: "错误"
	        		});
	        	}
        	});
     }
        
